import { baseRequest } from '@/utils/request'
import tool from '@/utils/tool'
import sysConfig from '@/config/index'

const request = (url, ...arg) => baseRequest(`/ai/chat/` + url, ...arg)

/**
 * AI对话接口管理器
 *
 * @author poker
 * @date  2025/02/28 16:07
 **/
export default {
	// 发送对话消息
	sendMessage(data, onMessage, onError) {
		const url = `/api/ai/chat/send`
		const body = JSON.stringify({
			message: data.message,
			sessionId: data.sessionId
		})

		// 使用fetch API发送POST请求并处理SSE响应
		const controller = new AbortController()
		const signal = controller.signal

		const token = tool.data.get('TOKEN')
		var tokenname = sysConfig.TOKEN_NAME;
		fetch(url, {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json',
				'Accept': 'text/event-stream',
				'token':  sysConfig.TOKEN_PREFIX + token
			},
			body: body,
			signal: signal
		})
		.then(response => {
			if (!response.ok) {
				throw new Error(`HTTP error! Status: ${response.status}`)
			}

			const reader = response.body.getReader()
			const decoder = new TextDecoder()

			let buffer = ''
				function read() {
					reader.read().then(({ done, value }) => {
						if (done) {
							// 处理缓冲区中剩余的数据
							if (buffer.trim() && onMessage) {
								onMessage(buffer.trim())
							}
							return
						}

						const text = decoder.decode(value, { stream: true })
						console.log('收到服务器数据--->:', text)

						// 将新数据添加到缓冲区
						buffer += text

						// 查找完整的消息
						const lines = buffer.split('\n')
						// 保留最后一行（可能不完整）作为新的缓冲区
						buffer = lines.pop() || ''

						lines.forEach(line => {
							line = line.trim()
							if (!line) return

							// 处理data:前缀的行
							if (line.startsWith('data:')) {
								line = line.substring(5).trim()
							}

							// 发送非空消息
							if (line && onMessage) {
								onMessage(line)
							}
						})

						read()
					})
				.catch(error => {
					if (onError) onError(error)
				})
			}

			read()
		})
		.catch(error => {
			if (onError) onError(error)
		})

		// 返回一个控制器对象，用于中止请求
		return {
			close: () => controller.abort()
		}
	},

	// 获取会话列表
	getSessions() {
		return request('sessions', {}, 'get')
	},

	// 获取指定会话的消息记录
	getMessages(sessionId) {
		return request(`messages/${sessionId}`, {}, 'get')
	},

	// 删除会话
	deleteSession(sessionId) {
		return request(`delete/${sessionId}`, {}, 'post')
	},

	// 向量检索
	vectorSearch(query) {
		return request('vector-search', { query }, 'post')
	},

	// 生成SQL
	generateSQL(data) {
		return request('sql-generate', data, 'post')
	},

	// 执行SQL
	executeSQL(sql) {
		return request('sql-execute', sql , 'post')
	}
}
